from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
# Create your views here.
from oauth.utils import generic_access_token

"""
用户点击 qq登录按钮的时候,前端发送一个 ajax请求, 后端将 生成的url 返回给前端

GET     /oauth/qq/statues/
"""
from django.conf import settings

# from mall import settings
class OauthQQURLView(APIView):

    """
    生成的url
    """

    def get(self,request):

        state = '/'

        #1.创建对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state)
        #2.调用对象的方法,获取url
        url = oauth.get_qq_url()
        # url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101474184&redirect_uri=http://www.meiduo.site:8080/oauth_callback.html&state=test"

        return Response({'login_url':url})


"""
当用户扫描成功之后,腾讯服务器会生成一个code,我们前端需要将code返回给 后端

接收code, 通过code换取token

GET     /oauth/qq/users/?code=xxx


"""
from rest_framework import status
from .models import OAuthQQUser
from oauth.serializer import OauthQQUserSerializer
class OauthQQUserView(APIView):


    def get(self,request):
        #''
        #1.接收code,
        code = request.query_params.get('code')

        if code is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        #2.通过code换取token

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        access_token = oauth.get_access_token(code)

        openid = oauth.get_open_id(access_token)


        # 获取到openid之后,我们要查询一下数据库 是否含有这个 openid
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果没有 则说明用户没绑定过
            """
            1. openid是比较敏感的数据,我们最好对这个数据进行一个加密
            2. 我们这个数据最好设置一个有效期

            """

            # 要将 openid 进行加密处理
            access_token = generic_access_token(openid)

            return Response({'access_token':access_token})
        else:
            #没有异常走 else
            #如果有 则说明用户绑定过
            # 应该跳转到首页去
            # 登录成功了,我们应该返回 token

            from rest_framework_jwt.settings import  api_settings

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(qquser.user)
            token = jwt_encode_handler(payload)


            return Response({
                'token':token,
                'username':qquser.user.username,
                'user_id':qquser.user.id
            })

    """
    当用户输入完绑定信息之后,前段应该将 手机号,密码,短信验证码,openid(处理过的)传递给后端

    1. 接收数据
    2. 对数据进行校验(手机号,密码,短信验证码,openid(处理过的))
        2.1 短信验证码
        2.2 openid(处理过的)
        2.3 根据手机号查询用户信息,判断是否存在

    3. 保存数据
    4. 返回响应

    POST

    """
    def post(self,request):
        # 1. 接收数据
        data = request.data
        # 2. 对数据进行校验
        serializer = OauthQQUserSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        # 3. 保存数据
        qquser = serializer.save()
        # 4. 返回响应
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(qquser.user)
        token = jwt_encode_handler(payload)

        return Response({
            'token': token,
            'username': qquser.user.username,
            'user_id': qquser.user.id
        })









from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

#1.创建序列化器
#secret_key             秘钥,我们一般使用的是 settings文件中的 SECRET_KEY
# expires_in=None       过期时间,单位是秒数
serializer = Serializer(settings.SECRET_KEY,3600)

#2. 组织数据
data = {'openid':'1234567890'}

#3. 对数据进行加密
token = serializer.dumps(data)

"""
eyJpYXQiOjE1NDE2NzA2NzEsImV4cCI6MTU0MTY3NDI3MSwiYWxnIjoiSFMyNTYifQ.
eyJvcGVuaWQiOiIxMjM0NTY3ODkwIn0.
vK3XB5n48e_bj-qFSwxDD8mPp7_TV_hrOi2gTDlJqXo

"""


#解密

serializer.loads(token)







#有效期
serializer = Serializer(settings.SECRET_KEY,1)

#2. 组织数据
data = {'openid':'1234567890'}

#3.加密
token = serializer.dumps(data)


#解密

serializer.loads(token)







